package com.jelly.web.modules.system.permission.service.impl;

import com.jelly.common.util.ListUtil;
import com.jelly.common.util.StringUtils;
import com.jelly.common.util.back.FilterChainDefinitionsUtil;
import com.jelly.common.util.back.ShiroUtil;
import com.jelly.common.util.web.BuildTreeUtil;
import com.jelly.common.web.tree.Tree;
import com.jelly.config.shiro.token.TokenUtil;
import com.jelly.web.modules.system.permission.dao.PermissionAndRoleMapper;
import com.jelly.web.modules.system.permission.dao.PermissionMapper;
import com.jelly.web.modules.system.permission.domain.Permission;
import com.jelly.web.modules.system.permission.domain.PermissionAndRole;
import com.jelly.web.modules.system.permission.domain.PermissionAndRoleExample;
import com.jelly.web.modules.system.permission.domain.PermissionExample;
import com.jelly.web.modules.system.permission.service.IPermissionService;
import com.jelly.web.modules.staff.user.domain.UserAndRoleAndPermission;
import com.jelly.web.modules.staff.user.service.IUserService;
import com.jelly.web.modules.system.role.service.IRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @创建人 ql
 * @创建时间 2018-08-17 12:06
 * @功能描述: 权限接口实现类
 **/
@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionAndRoleMapper permissionAndRoleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private IRolePermissionService rolePermissionService;
    @Autowired
    private IUserService userService;
    /**
     * 获取权限ree数结构
     * @return
     */
    @Override
    public Tree<Permission> getTreePermission(Permission permission) {

        List<Permission> list = getPermissionList(permission);
        List<Tree<Permission>> trees = new ArrayList<Tree<Permission>>();

        if(ListUtil.isNotList(list)){

            for (Permission dept : list){
                Tree<Permission> tree = new Tree<Permission>();
                tree.setId(dept.getPerId());
                tree.setParentId(dept.getParentId());
                tree.setText(dept.getPerName());
                if("0".equals(dept.getParentId())){
                    Map map = new HashMap();
                    map.put("opened",true);
                    tree.setState(map);
                }
                trees.add(tree);
            }

        }

        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<Permission> t = BuildTreeUtil.build(trees);
        return t;
    }

    /**
     * 查询拦截详情
     */
    @Override
    public List<PermissionAndRole> loadFilterChainDefinitions() {
        return permissionAndRoleMapper.selectByExample(new PermissionAndRoleExample());
    }

    /**
     * 查询权限id
     * @param url 权限URL
     * @return
     */
    @Override
    public List<Permission> getPermissionIdList(String url) {

        if(StringUtils.isNotBlank(url)){
            PermissionExample example = new PermissionExample();
            example.createCriteria().andPerHrefEqualTo(url);
            return permissionMapper.selectByExample(example);
        }

        return null;
    }
    /**
     * 通过id查询权限
     * @return
     */
    @Override
    public Permission getPermissionId(String permissionId) {
        return permissionMapper.selectByPrimaryKey(permissionId);
    }
    /**
     * 查询权限列表
     * @return
     */
    @Override
    public List<Permission> getPermissionList(String isState) {
        PermissionExample permissionExample = new PermissionExample();
        permissionExample.createCriteria().andIsStateEqualTo(isState);
        return permissionMapper.selectByExample(permissionExample);
    }

    /**
     * 查询权限列表
     * @return
     */
    @Override
    public List<Permission> getPermissionList(Permission permission) {
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();

        if(StringUtils.isNotBlank(permission.getIsState())){
            criteria.andIsStateEqualTo(permission.getIsState());
        }

        if(StringUtils.isNotBlank(permission.getPerName())){
            criteria.andPerNameEqualTo(permission.getPerName());
        }

        if(StringUtils.isNotBlank(permission.getPerRoute())){
            criteria.andPerRouteEqualTo(permission.getPerRoute());
        }

        if(StringUtils.isNotBlank(permission.getPerHref())){
            criteria.andPerHrefEqualTo(permission.getPerHref());
        }
        permissionExample.setOrderByClause("stort asc");

        return permissionMapper.selectByExample(permissionExample);

    }


    /**
     * 修改权限
     * @return
     */
    @Override
    public boolean updatePermission(Permission permission) {

        if(StringUtils.isBlank(permission.getPerId())){
            if(StringUtils.isNotBlank(permission.getBaseId())){
                permission.setPerId(permission.getBaseId());
            }else{
                return false;
            }
        }
        permission.setUpdateDate(new Date());
        permission.setUpdateId(TokenUtil.getUserId());

        boolean bol = permissionMapper.updateByPrimaryKeySelective(permission) >0;

        if(bol){
            insterPermission(permission.getPerId());
        }

        return bol;
    }

    /**
     * 新增权限
     * @return
     */
    @Override
    public boolean addPermission(Permission permission) {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        permission.setPerId(id);
        permission.setAddDate(new Date());
        permission.setAddId(TokenUtil.getUserId());
        boolean bol = permissionMapper.insertSelective(permission) > 0;
        if(bol){
            rolePermissionService.addRolePermission("1",id);
            insterPermission(id);
        }
        return bol;
    }

    /**
     * 删除权限
     * @return
     */
    @Override
    public boolean delectPermission(String permissionId) {
        if(permissionMapper.deleteByPrimaryKey(permissionId) > 0){
            //更新拦截信息
            FilterChainDefinitionsUtil.updatePermission();
            return true;
        }
        return false;
    }

    protected void insterPermission(String perId){
        //更新拦截信息
        FilterChainDefinitionsUtil.updatePermission();
        //更新用户的权限信息
        List<UserAndRoleAndPermission> list = userService.getUserAndRoleAndPermission(perId);
        if(ListUtil.isNotList(list)){
            for (UserAndRoleAndPermission user:list){
                ShiroUtil.updateSession(user.getLoginAccount());
            }
        }
    }

}
